import { messages, getToken } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Affix, message, Button, Modal, Icon, Input, Checkbox, Popconfirm, Popover } from 'antd'
import errorMessage from 'share/errorMessage';
import ApproveBar from 'components/template/approve-bar'
import financeAuditService from './finance-audit.service'
import baseService from 'share/base.service'
import expenseReportService from "containers/expense-report/expense-report.service"
import borrowService from 'containers/loan-billing/borrow-and-return.service'
import Condition from 'components/condition'
import invoiceBagApproveService from 'containers/financial-management/invoice-bag-approve/invoice-bag-approve.service'
import ApproveExpenseReportService from "containers/approve/expense-report/approve-expense-report.service";
import autoAuditService from 'containers/finance-setting/auto-audit/auto-audit.service'
import ExpenseCheckResult from "../../expense-report/components/expense-check-result";
import AuditNoticeModal from './components/audit-notice-modal'
import AutoAuditErrorModal from "./components/auto-audit-error-modal"
import ModalAddSign from "../invoice-bag-approve/components/modal-add-sign";
import ModalRemoveFromBag from "./components/modal-remove-from-bag";
import ModalDeleteConfirm from "./components/modal-delete-confirm";
import bagFunction from "../invoice-bag-approve/invoice-bag-approve.function";
import 'styles/approve/request/request.scss'
import "styles/financial-management/new-finance-audit/slide-expense-report-detail.scss"

const { If } = Condition;
const { TextArea } = Input;
const { getBatchButtons, moreButtonList } = bagFunction;

class AuditApplicationDetail extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      passLoading: false,
      rejectLoading: false,
      noticeLoading: false,
      printLoading: false,
      checkLoading: false,
      modalShow: false,
      paperReject: false,
      paperLoading: false,
      allLoading: false,
      rejectReason: '',
      approvalTxtString: '',
      event: [],
      invoiceNumber: 0,
      failedInvoices: [],
      certificateVisible: false,
      certificateLink: '',
      autoAuditLoading: false,
      hasAutoAudit: null,
      additionalItems: [],
      showAdditional: false,
      companyOIDs: [],
      enableManual: false, //是否开启人工审核时手动调用
      showCheckResult: false,
      checkResult: [],
      rePassLoading: false,
      hangUpLoading: false,
      hangUpVisible: false,
      auditReason: '',
      retainHangUpLabel: false, //是否保留暂挂标签
      noticeVisible: false,
      autoAuditErrorList: [], //自动审核报错信息
      addSignVisible: false, //加签弹框
      addSignInfo: {}, //加签信息
    };
    this.shouldRefreshDetail = false;
  }

  attachmentOIDs = [];

  componentDidMount() {
    const { entityType } = this.props;
    let retainHangUpLabel = entityType === 1002 ?
      localStorage.getItem('expense-retain-hangup-tag'):
      localStorage.getItem('loan-retain-hangup-tag');
    this.setState({ retainHangUpLabel: retainHangUpLabel === 'true' });
    this.getThirdTnterface(this.props);
  }

  getThirdTnterface = props => {
    const { failedInvoices, entityType, companyOid, formOID, loginUser, entityOID } = props;
    this.setState({
      failedInvoices,
      invoiceNumber: failedInvoices ? failedInvoices.length : 0
    });
    let thirdInterface = entityType === 1002 ? [
      expenseReportService.canAutoAudit(companyOid),
      expenseReportService.getPrintCertificate('Exp_Report_Print_Doc'),
      autoAuditService.getAutoSetting()
    ] : [
      expenseReportService.getPrintCertificate('CA_PRINT_DOCUMENT')
    ];
    thirdInterface.push(ApproveExpenseReportService.isCounterSignEnable(
      companyOid,
      formOID,
      'enableAddSign',
      loginUser.userOID,
      entityOID,
      entityType
    ));
    Promise.all(thirdInterface).then(res => {
      let params = entityType === 1002 ? {
        hasAutoAudit: res[0].data,
        certificateVisible: !!res[1].data,
        certificateLink: res[1].data.link,
        enableManual: res[2] && res[2].data.enableManual,
        showAdditional: res[3] && res[3].data.enabled,
        companyOIDs: res[3] && res[3].data.approvalAddSignScope.companyOIDs
      } : {
        certificateVisible: !!res[0].data,
        certificateLink: res[0].data.link,
        showAdditional: res[1] && res[1].data.enabled,
        companyOIDs: res[1] && res[1].data.approvalAddSignScope.companyOIDs
      };
      this.setState(params)
    }).catch(err => {
      console.log(err);
      message.error(messages('expense-14.key1')/*系统异常*/);
    });
  };

  //返回
  goBack = (isNeedRefreshList) => this.props.goBack(isNeedRefreshList);

  handleApprovePass = temp => {
    let isHandle = !(typeof temp === 'object' && temp.hasOwnProperty('reason'));
    let { approvalTxtString, event, additionalItems } = this.state;
    const { entityOID, entityType, approvalHistory = [] } = this.props;
    let events, additionalUsers = [];
    let value = isHandle ? approvalTxtString : (temp.reason ? temp.reason : approvalTxtString);
    events = isHandle ? event : (temp.honestEvent || []);
    additionalUsers = isHandle ? additionalItems : (temp.additionalItems || []);
    let preApproveOIDs = [];
    let additionalHaveApprovedNames = [];  //加签人中已审批的用户名
    approvalHistory.map(item => {
      item.operation === 2001 && (preApproveOIDs.push(item.operatorOID))
    });
    let additionalOIDs = additionalUsers.map(item => item.userOID);
    additionalOIDs.map((OID, index) => {
      if (preApproveOIDs.indexOf(OID) > -1) {
        additionalHaveApprovedNames.push(additionalUsers[index].fullName)
      }
    });
    let ids = [];
    events.map(item => {
      ids.push(item.id);
    });
    let params = {
      approvalTxt: value ? value.trim() : value,
      entities: [{
        entityOID,
        entityType,
        countersignApproverOIDs: additionalOIDs,
        attachmentOIDs: this.attachmentOIDs
      }],
      conditionIds: ids
    };
    if (additionalHaveApprovedNames.length) {
      Modal.confirm({
        title: `${additionalHaveApprovedNames.join('、')} ${messages('expense-14.key2')/*已经审批通过，是否继续*/}？`,
        onOk: () => this.fetchAuditPass(params)
      });
    } else {
      this.fetchAuditPass(params);
    }
  };

  fetchAuditPass = params => {
    const { addSignInfo } = this.state;
    addSignInfo.signUserType && (params.entities[0].signUserType = addSignInfo.signUserType);
    this.setState({ passLoading: true, params });
    financeAuditService.auditPass(params).then(res => {
      const { entityOID, entityType } = this.props;
      if (res.status !== 200) {
        message.error(messages('common.operate.filed')/*操作失败*/);
        return ;
      }
      //报销单审核的时候做重新检查 并展示检查结果
      if (entityType === 1002 && res.data.checkResult) {
        this.setState({
          passLoading: false,
          showCheckResult: res.data.checkResult[entityOID] && res.data.checkResult[entityOID].length,
          rePassLoading: false,
          checkResult: res.data.checkResult[entityOID] || []
        }, this.shouldRefresh);
        if (res.data.checkResult[entityOID] && res.data.checkResult[entityOID].length) return ;
      }
      if (res.data.failNum === 0) {
        message.success(messages('common.operate.success')/*操作成功*/);
        this.setState({ passLoading: false });
        this.goBack(true)
      } else {
        this.setState({ passLoading: false });
        if (res.data.failReason && res.data.failReason[entityOID]) {
          message.error(res.data.failReason[entityOID]);//'的报销单审核失败'
          return !1;
        }
        message.error(messages('common.operate.filed')/*操作失败*/)
      }
    }).catch(e => {
      this.setState({ passLoading: false });
      e.response.data.message ? message.error(`${messages('common.operate.filed')/*操作失败*/}，${e.response.data.message}`) : message.error(messages('common.operate.filed')/*操作失败*/);
    })
  };

  handleAuditRepass = () => {
    const { params } = this.state;
    this.setState({ rePassLoading: true }, () => {
      this.fetchAuditPass(Object.assign({}, params, {ignoreCheck: true}));
    });
  };

  shouldRefresh = () => {
    const { checkResult } = this.state;
    this.shouldRefreshDetail = !!checkResult.filter(i => i.externalPropertyName && String(i.externalPropertyName) !== '9002').length;
  };

  handleCancleAuditRepass = () => {
    const { afterClose } = this.props;
    this.setState({ showCheckResult: false, rePassLoading: false }, () => afterClose(this.shouldRefreshDetail));
  };

  invoiceNumberPass = params => {
    const { invoiceEnabled } = this.props;
    this.attachmentOIDs = params.attachmentOIDs;
    this.setState({ approvalTxtString: params.reason, event: params.honestEvent, additionalItems: params.additionalItems });
    const { invoiceNumber } = this.state;
    invoiceNumber !== 0 && invoiceEnabled ?
      this.setState({ modalShow: true }) :
      this.handleApprovePass(params);
  };

  //检查差补费用
  checkInvoiceIsSubsidy = params => {
    const { selectedExpense, expenseReportInvoices } = this.props;
    let subsidyInvoicesOID = [];
    selectedExpense && selectedExpense.map(oid => {
      let invoiceItem = expenseReportInvoices.filter(item => item.invoiceOID === oid)[0];
      let subsidyType = invoiceItem && invoiceItem.invoiceView && invoiceItem.invoiceView.expenseTypeSubsidyType;
      subsidyType === 1 && subsidyInvoicesOID.push(oid);
    });
    if (subsidyInvoicesOID.length > 0) {
      Modal.confirm({
        title: (
          <div>
            <div>{messages('expense-14.key3')/*差补费用不支持批量驳回*/}</div>
            <div>
              <span style={{color: '#f5222d'}}>{messages('expense-14.key4')/*将为您自动取消勾选差补费用！*/}</span>
              {messages('expense-14.key5')/*是否继续？*/}
            </div>
          </div>
        ),
        okText: messages('expense-14.key6')/*继续*/,
        onOk: () => this.cancelSubsidyInvoice(subsidyInvoicesOID, params)
      });
    }
    return subsidyInvoicesOID.length > 0;
  };

  //取消勾选差补费用
  cancelSubsidyInvoice = (subsidyInvoicesOID, params) => {
    const { selectedExpense, onSelectExpense = () => {} } = this.props;
    let selectedKeys = [];
    selectedExpense && selectedExpense.map(oid => !~subsidyInvoicesOID.indexOf(oid) && selectedKeys.push(oid));
    onSelectExpense(selectedKeys);
    if (selectedKeys.length === 0) {
      Modal.info({
        title: messages('expense-14.key7')/*请先勾选费用！*/
      })
    } else {
      setTimeout(() => this.handleApproveReject(params))
    }
  };

  handleApproveReject = params => {
    const { options, formType } = this.props;
    this.attachmentOIDs = params.attachmentOIDs;
    if (this.checkInvoiceIsSubsidy(params)) {
      return;
    }
    this.setState({ rejectLoading: true, rejectReason : params.reason, event: params.honestEvent }, () => {
      let fp = options.auditBaseConfig[formType === 3004 ? 'corpReviewExpBeforeReceive' : 'reviewExpBeforeReceive'];
      if(fp) {
        this.setState({ paperReject: true });
      } else {
        this.handlePaperReject(false);
      }
    });
  };

  handlePaperReject = (isPaper, modal = false) => {
    modal && this.setState({ paperLoading: true });
    const {
      info, entityOID, entityType, selectedExpense, afterClose, expenseReportInvoices, options: { auditBaseConfig }
    } = this.props;
    const { event, rejectReason }  = this.state;
    let ids = [];
    event.map(item => {
      ids.push(item.id);
    });
    if(selectedExpense && selectedExpense.length > 0) {
      let runService = (deleteBagRelation, afterSuccess) => {
        let params = {
          approvalTxt: rejectReason,
          expenseReportOID: entityOID,
          invoiceOIDs: selectedExpense,
          conditionIds: ids,
          needChargeBack: isPaper,
          attachmentOIDs: this.attachmentOIDs,
          deleteBagRelation
        };
        this.setState({ paperLoading: true, rejectLoading: true });
        financeAuditService.rejectExpense(params).then(res => {
          let { failReason, successNum, failNum } = res.data;
          this.setState({
            paperLoading: false,
            rejectLoading: false,
            rejectReason: ''
          });
          this.approveBarRef && this.approveBarRef.clearData();
          this.attachmentOIDs = [];
          if (res.status === 200 && failNum === 0) {
            message.success(messages('common.operate.success')/*操作成功*/);
            afterSuccess();
          } else {
            let firstError = failReason[Object.keys(failReason)[0]];
            message.info(messages('expense-14.key8',{arg1: successNum,arg2: failNum,arg3: firstError})/*操作成功{arg1}条，失败{arg2}条，失败原因为：{arg3}*/);
            afterClose(true);
          }
        }).catch(e => {
          this.setState({ paperLoading: false, rejectLoading: false });
        });
      };
      if(expenseReportInvoices.length === selectedExpense.length) {
        ModalDeleteConfirm.open({
          visible: true,
          info,
          onOk: deleteBagRelation => {
            if (ids.length === 0 && auditBaseConfig.rejectWithCondition && entityType === 1002) {
              Modal.confirm({
                title: messages('expense-14.key10')/*确认驳回*/,
                content: messages('expense-14.key11')/*未产生信用事件，是否确定驳回？*/,
                onOk: () => runService(deleteBagRelation, () => this.goBack(true)),
                onCancel: () => this.setState({ paperLoading: false, rejectLoading: false })
              })
            } else {
              runService(deleteBagRelation, () => this.goBack(true));
            }
          },
          afterClose: () => {
            this.setState({ paperLoading: false, rejectLoading: false });
          }
        })
      } else {
        runService(false, () => afterClose(true));
      }
    } else {
      let rejectService = () => {
        let params = {
          approvalTxt: rejectReason,
          entities: [{
            entityOID,
            entityType,
            attachmentOIDs: this.attachmentOIDs
          }],
          conditionIds: ids,
          needChargeBack: isPaper
        };
        financeAuditService.auditReject(params).then(res => {
          if (res.status === 200 && res.data.failNum === 0) {
            message.success(messages('common.operate.success')/*操作成功*/);
            this.setState({ rejectLoading: false });
            this.goBack(true)
          } else {
            this.setState({ rejectLoading: false });
            modal && this.setState({ paperReject: false, paperLoading: false });
            let errorMessage = res.data.failReason[params.entities[0].entityOID];
            message.error(errorMessage);
          }
        }).catch(() => {
          this.setState({ rejectLoading: false });
          modal && this.setState({ paperReject: false, paperLoading: false });
          message.error(messages('common.operate.filed')/*操作失败*/)
        });
      };
      if (ids.length === 0 && auditBaseConfig.rejectWithCondition && entityType === 1002) {
        Modal.confirm({
          title: messages('expense-14.key10')/*确认驳回*/,
          content: messages('expense-14.key11')/*未产生信用事件，是否确定驳回？*/,
          onOk: () => rejectService(),
          onCancel: () => {
            this.setState({ rejectLoading: false });
            modal && this.setState({ paperReject: false, paperLoading: false });
          }
        });
      } else {
        rejectService();
      }
    }
  };

  handlePrint = () => {
    const { entityOID } = this.props;
    this.setState({ printLoading: true });
    if(this.props.entityType===1002){
      baseService.printExpense(entityOID).then(res => {
        this.setState({ printLoading: false });
        window.open(res.data.link ,"_blank")
      });
    }
    else{
      borrowService.printLoanApplication(entityOID).then(res => {
        this.setState({ printLoading: false });
        window.open(res.data.link ,"_blank")
      });
    }
  };

  handleAuditCheck = () => {
    const { failedInvoices } = this.state;
    this.setState({ checkLoading: true });
    expenseReportService.recheckInvoice(failedInvoices).then(res => {
      if(res.data.failedCount === 0){
        this.setState({ invoiceNumber:0, failedInvoices:[] });
        message.success(messages('expense-14.key12')/*发票查验成功*/);
      } else {
        this.setState({ invoiceNumber:res.data.failedCount, failedInvoices:res.data.failedList })
        message.warn(messages('expense-14.key13')/*有查验失败的发票信息*/);
      };
      if (res.data.successList.length > 0) {
        this.props.afterClose(true, res.data.failedList);
      }
      this.setState({ checkLoading: false });
    });
  };

  closeModal = () => {
    this.setState({ modalShow: false })
  };

  handleAutoAudit = () => {
    const { entityOID, entityType } = this.props;
    let params = {
      entityOid: entityOID,
      auditType: entityType === 1002 ? 1001 : 1002,
    };
    this.setState({autoAuditLoading: true});
    expenseReportService.autoAudit(params).then(res => {
      this.setState({autoAuditLoading: false});
      const { auto, autoAuditMessageList, content } = res.data;
      if (auto) {
        message.success(messages('expense-14.key14')/*自动审核通过*/);
        this.props.afterClose(true);
      } else if (autoAuditMessageList && autoAuditMessageList.length) {
        this.setState({ autoAuditErrorList: autoAuditMessageList });
      } else {
        message.error(content);
        this.props.afterClose(true);
      }
    }).catch(e => {
      this.setState({autoAuditLoading: false});
      message.error(e.response.data.message);
    })
  };

  //打印凭证
  handlePrintCertificate = () => {
    const { businessCode, parentBusinessCode, company } = this.props;
    let { certificateLink } = this.state;
    certificateLink += `&access_token=${JSON.parse(getToken()).access_token}`;
    let state = `businessCode=${businessCode}&companyOID=${company.companyOID}`;
    parentBusinessCode && (state += `&parentBusinessCode=${parentBusinessCode}`);
    certificateLink += `&state=${btoa(state)}`;
    window.open(certificateLink, '_blank')
  };

  //暂挂
  handleHangUp = () => {
    const { entityOID, entityType } = this.props;
    const { auditReason, retainHangUpLabel } = this.state;
    let params = {
      entityOID,
      entityType,
      retainLabel: retainHangUpLabel,
      message: auditReason
    };
    this.setState({ hangUpLoading: true });
    autoAuditService.auditHangUp(params).then(() => {
      this.setState({
        hangUpLoading: false,
        hangUpVisible: false,
        auditReason: ''
      });
      this.goBack(true);
      message.success(messages('common.operate.success')/*操作成功*/)
    }).catch(e => {
      this.setState({ hangUpLoading: false });
      errorMessage(e.response);
    })
  };

  changeHangUpTag = e => {
    const { entityType } = this.props;
    this.setState({ retainHangUpLabel: e.target.checked });
    if (entityType === 1002) {
      localStorage.setItem('expense-retain-hangup-tag', e.target.checked);
    } else {
      localStorage.setItem('loan-retain-hangup-tag', e.target.checked);
    }
  };

  //人工审核标记
  handleManualAudit = flag => {
    const { selectedExpense, entityOID } = this.props;
    let params = {
      invoiceOIDs: selectedExpense,
      expenseReportOID: entityOID,
      manualAudit: flag
    };
    this.setState({ allLoading: true });
    autoAuditService.setManualAudit(params).then(() => {
      this.setState({ allLoading: false });
      message.success(messages('common.operate.success')/*操作成功*/);
      this.props.afterClose('invoiceList');
    }).catch(e => {
      this.setState({ allLoading: false });
      errorMessage(e.response);
    })
  };


  //获取批量操作费用时的按钮
  getManualAuditButtons = () => {
    const { selectedExpense, expenseReportInvoices } = this.props;
    let buttons = [];
    selectedExpense && selectedExpense.map(oid => {
      let invoiceItem = expenseReportInvoices.filter(item => item.invoiceOID === oid)[0];
      let manualAudit = invoiceItem && invoiceItem.invoiceView && invoiceItem.invoiceView.manualAudit;
      if (!buttons.some(item => item.key === (manualAudit ? 'manualAuditN' : 'manualAuditY'))) {
        buttons.push({
          key: manualAudit ? 'manualAuditN' : 'manualAuditY',
          sortId: manualAudit ? 0 : 1,
          text: manualAudit ? messages('expense-14.key15')/*标记待审核*/ : messages('expense-14.key16')/*标记已审核*/,
          onClick: () => this.handleManualAudit(!manualAudit)
        })
      }
    });
    buttons.sort((a, b) => b.sortId - a.sortId);
    return buttons;
  };

  handleDeleteInvoice = () => {
    const { selectedInvoice, afterClose } = this.props;
    this.setState({ allLoading: true });
    invoiceBagApproveService.batchDeleteInvoice(selectedInvoice.map(item => {
      return {id: item.id, invoiceOID: item.invoiceOID || ''}
    }))
      .then(() => {
        message.success(messages('common.delete.success',{arg1: ""})/*{arg1} 删除成功*/);
        afterClose('receiptList');
      })
      .finally(() => this.setState({ allLoading: false }))
  };

  handleCheckInvoice = checkTag => {
    const { entityOID, selectedInvoice, afterClose } = this.props;
    const checkTagName = checkTag === 'CHECKED' ? messages('expense-14.key17')/*已核对*/ : messages('expense-14.key18')/*未匹配*/;
    const params = {
      checkTag,
      receiptIds: selectedInvoice.map(item => item.id),
      checkSource: 1,
      entityCode: entityOID
    };
    this.setState({ allLoading: true });
    invoiceBagApproveService.batchCheckInvoice(params)
      .then(() => {
        message.success(messages('expense-14.key19',{arg1: selectedInvoice.length,arg2: checkTagName})/*{arg1} 笔发票更新为{arg2}*/);
        afterClose('receiptList');
      })
      .finally(() => this.setState({ allLoading: false }))
  };

  handleButtonClick = key => {
    // 从发票袋移除
    if (key === 'removeFromBag') {
      ModalRemoveFromBag.open({
        visible: true,
        info: this.props.info || {},
        reason: this.approveBarRef.props.form.getFieldValue('reason'),
        afterClose: needBack => needBack ? this.goBack(true) : this.props.afterClose(true)
      }, this)
    }
  };

  buttonsMap = {
    'removeFromBag': {
      key: 'removeFromBag',
      text: messages('expense-14.key497')/*从发票袋移除*/,
      onClick: () => this.handleButtonClick('removeFromBag')
    },
    'print': {
      key: 'print',
      text: messages('common.print')/*打印*/,
      onClick: this.handlePrint
    },
    'hangUp': {
      text: messages('expense-14.key20')/*暂挂*/,
      onClick: () => this.setState({ hangUpVisible: true })
    },
    'noticeBtn': {
      text: messages('expense-14.key21')/*通知/暂挂*/,
      onClick: () => this.setState({
        noticeVisible: true,
        auditReason: this.approveBarRef.props.form.getFieldValue('reason')
      })
    },
    'autoAudit': {
      text: messages('expense-14.key22')/*自动审核*/,
      onClick: this.handleAutoAudit
    },
    'auditCheck': {
      text: messages('expense-14.key23')/*查验发票*/,
      onClick: this.handleAuditCheck
    },
    'print-certificate': {
      text: messages('expense-14.key24')/*打印凭证*/,
      onClick: this.handlePrintCertificate
    },
    'additional': {
      text: messages('expense-14.key25')/*加签*/,
      onClick: () => this.setState({ addSignVisible: true })
    },
    'autoTransfer': {
      key: 'autoTransfer',
      text: messages('expense-14.key26')/*转交*/,
      onClick: () => this.approveBarRef.setState({ autoTransferVisible: true })
    }
  };

  getMoreButtons = () => {
    const { invoiceNumber, hasAutoAudit, certificateVisible, showAdditional, enableManual } = this.state;
    const {
      selectedExpense, selectedInvoice, status, invoiceEnabled, isAuditInApproveStatus, customFormPropertyMap, info
    } = this.props;
    if (selectedExpense.length || selectedInvoice.length) {
      return [];
    } else {
      let moreButtons = ['hangUp', 'noticeBtn'];
      info.expenseReportBagCode && moreButtons.push('removeFromBag');
      ((!isAuditInApproveStatus && hasAutoAudit) || enableManual) && moreButtons.push('autoAudit');
      invoiceNumber > 0 && invoiceEnabled && moreButtons.push('auditCheck');
      certificateVisible && moreButtons.push('print-certificate');
      isAuditInApproveStatus && showAdditional && moreButtons.push('additional');
      status === 1002 && customFormPropertyMap && customFormPropertyMap['approvalIsDeliver'] === 'true' && moreButtons.push('autoTransfer');
      return moreButtons;
    }
  };

  getShowButtons = (isMoreButton, buttons1, buttons2) => {
    const { selectedExpense, selectedInvoice, formType } = this.props;
    if (selectedInvoice.length) {
      return [];
    }
    if (selectedExpense.length) {
      return isMoreButton ? [] : buttons1.includes('reject') ? ['reject'] : [];
    }
    let outButtons = [], moreButtons = [];
    buttons1.concat(buttons2).map(key => {
      if (moreButtonList(formType).includes(key)) {
        moreButtons.push(key);
      } else {
        outButtons.push(key);
      }
    });
    outButtons.delete('print');
    return isMoreButton ? moreButtons : outButtons;
  };

  getCustomButtons = (buttons1, buttons2) => {
    const { invoiceNumber } = this.state;
    const { selectedExpense, selectedInvoice, formType } = this.props;
    if (selectedInvoice && selectedInvoice.length) {
      return getBatchButtons({
        invoices: selectedInvoice,
        deleteFunc: this.handleDeleteInvoice,
        checkFunc: this.handleCheckInvoice
      });
    }
    if (selectedExpense && selectedExpense.length) {
      return this.getManualAuditButtons();
    }
    let buttons = [];
    buttons1.concat(buttons2).map(key => {
      if (!(moreButtonList(formType).includes(key)) && this.buttonsMap[key]) {
        this.buttonsMap[key].type = 'primary';
        key === 'auditCheck' && (this.buttonsMap[key].text = `${messages('expense-14.key23')/*查验发票*/}（${invoiceNumber}）`);
        buttons.push(this.buttonsMap[key]);
      }
    });
    buttons.sort((a, b) => (a.key === 'removeFromBag' && b.key === 'print') ? -1 : 0);
    return buttons;
  };

  render() {
    const {
      passLoading, rejectLoading, noticeLoading, printLoading, invoiceNumber, checkLoading,
      modalShow, paperReject, paperLoading, autoAuditLoading, certificateVisible,
      companyOIDs, showCheckResult, rePassLoading, checkResult, autoAuditErrorList,
      hangUpVisible, auditReason, retainHangUpLabel, hangUpLoading, noticeVisible, allLoading,
      addSignVisible, addSignInfo
    } = this.state;
    const { profile, applicantOID, entityType, businessCode, fullWidth, isWaitForAudit,
      entityOID, loginUser, customFormPropertyMap, selectedExpense, selectedInvoice,
      options: { auditBaseConfig }} = this.props;
    let moreButtons = this.getMoreButtons();
    let batchButtons = auditBaseConfig.reviewEditSuitable && auditBaseConfig.expenseBatchReject ? ['reject'] : [];
    let buttons = selectedInvoice.length ? [] :
      (selectedExpense.length ? batchButtons : ['pass', 'reject', 'print']);
    return isWaitForAudit && !(profile['er.disabled'] && entityType === 1002) ? (
      <Affix offsetBottom={0} className={`audit-bottom-bar bottom-bar bottom-bar-approve${fullWidth ? ' full-width' : ''}`}>
        <ApproveBar
          onRef={ref => this.approveBarRef = ref}
          withAttachments={entityType === 1002 || entityType === 3001}
          allLoading={passLoading || rejectLoading || noticeLoading || printLoading || autoAuditLoading || checkLoading || allLoading}
          signCompanyOIDs={companyOIDs}
          handleApprovePass={this.invoiceNumberPass}
          handleApproveReject={this.handleApproveReject}
          handleAuditNotice={reason => this.setState({ noticeVisible: true, auditReason: reason })}
          handleAuditPrint={this.handlePrint}
          handleApprovePrint={this.handlePrint}
          handleAutoAudit={this.handleAutoAudit}
          goBack={this.goBack}
          invoiceNumber={invoiceNumber}
          needHonest={entityType === 1002}
          applicantOID={applicantOID}
          businessCode={businessCode}
          handleAuditCheck={this.handleAuditCheck}
          handlePrintCertificate={this.handlePrintCertificate}
          handleApproveHangUp={() => this.setState({ hangUpVisible: true })}
          handleAddSign={() => this.setState({ addSignVisible: true })}
          editSignUser={() => this.setState({ addSignVisible: true })}
          handleButtonClick={this.handleButtonClick}
          entities={{
            approverOID: loginUser.userOID, //多级审核中chain上的第一个审批人不一定是当前审批人，暂无代理的情况下先取登录人oid
            entityOID: entityOID,
            entityType: entityType,
          }}
          audit
          customFormPropertyMap={customFormPropertyMap}
          batchNumber={selectedExpense ? selectedExpense.length : 0}
          btnShowMode={selectedExpense && selectedExpense.length > 0 ? 'all' : null}
          buttons={entityType === 3001 ? buttons : this.getShowButtons(false, buttons, moreButtons)}
          moreButtons={entityType === 3001 ? moreButtons : this.getShowButtons(true, buttons, moreButtons)}
          customButtons={entityType === 3001 ? [] : this.getCustomButtons(buttons, moreButtons)}
        />
        <Modal
          footer={
           <div>
             <Button onClick={this.closeModal} >{messages('common.cancel')/*取消*/}</Button>
             <Button onClick={() => {this.setState({modalShow: false}); this.handleAuditCheck();}} >{messages('common.invoiceNumber',{arg1: invoiceNumber})/*查验发票（{arg1}）*/}</Button>
             <Button onClick={this.handleApprovePass} type='primary' loading={passLoading}>{messages('expense-14.key27')/*审核通过*/}</Button>
           </div>
          }
          onCancel={this.closeModal}
          confirmLoading={passLoading}
          visible={modalShow}
          closable={false}
        >
          <div>
            <Icon type="exclamation-circle" style={{color:"#F7C243",fontSize:"30",float:"left"}}/><span style={{lineHeight:"30px",fontSize:"20",marginLeft:"10px"}}>{messages('expense-14.key28')/*有未查验或查验失败的发票信息*/}</span>
            <div style={{marginLeft:"40px",fontSize:"16px",color:"red",lineHeight:"30px"}}>{messages('expense-14.key29')/*是否仍然审核通过*/}</div>
            <p className='font-description' style={{margin: '16px 0 0 40px'}}>{messages('expense-14.key30')/*请至费用明细/发票模式，筛选标签\"查验失败\"查看*/}</p>
          </div>
        </Modal>
        <Modal onCancel={() => {this.setState({paperReject:false,rejectLoading:false})}}
               footer={
                 <div>
                   <Button type={'primary'} onClick={() => this.handlePaperReject(true,true)} loading={paperLoading} className={'okButton'}>{messages('expense-14.key31')/*驳回并退单*/}</Button>
                   <Button onClick={() => this.handlePaperReject(false,true)} loading={paperLoading} className={'cancelButton'}>{messages('common.reject')/*驳回*/}</Button>
                 </div>
               }
               width={350}
               className={'paper-modal'}
               visible={paperReject}
               closable={true}>
          <div style={{marginTop:'10px'}}>
            <Icon type="exclamation-circle" style={{color:"#F7C243",fontSize:"25",float:"left"}}/><span style={{lineHeight:"25px",fontSize:"16",marginLeft:"10px"}}>{messages('expense-14.key32')/*是否需要退回纸质单据？*/}</span>
          </div>
        </Modal>
        <Modal
          visible={hangUpVisible}
          title={messages('expense-14.key20')/*暂挂*/}
          onCancel={() => this.setState({ hangUpVisible: false, hangUpReason: '' })}
          footer={[
            <Button onClick={() => this.setState({ hangUpVisible: false, auditReason: '' })}>
              {messages('common.cancel')/*取消*/}
            </Button>,
            <Button type="primary" loading={hangUpLoading} onClick={this.handleHangUp}>
              {messages('expense-14.key20')/*暂挂*/}
            </Button>
          ]}
        >
          <TextArea
            rows={4}
            maxLength={2000}
            value={auditReason}
            style={{ marginBottom: 10 }}
            placeholder={messages('expense-14.key33')/*请输入暂挂原因*/}
            onChange={e => this.setState({ auditReason: e.target.value })}
          />
          <Checkbox checked={retainHangUpLabel} onChange={this.changeHangUpTag}>
            {messages('expense-14.key34')/*审核通过后，不清除暂挂标签*/}
          </Checkbox>
        </Modal>
        <AuditNoticeModal
          visible={noticeVisible}
          entityOID={entityOID}
          entityType={entityType}
          reason={auditReason}
          close={closePage => this.setState({ noticeVisible: false }, () => closePage && this.goBack(true))}
        />
        {/*报销单提交时检查结果*/}
        <ExpenseCheckResult
          visible={showCheckResult}
          checkResult={checkResult}
          submitLoading={rePassLoading}
          confirmSubmit={this.handleAuditRepass}
          confirmText={messages('expense-14.key27')/*审核通过*/}
          onCancel={this.handleCancleAuditRepass}
        />
        {/*自动审核报错弹框*/}
        {autoAuditErrorList.length > 0 && (
          <AutoAuditErrorModal
            type="report"
            entityOID={entityOID}
            errorList={autoAuditErrorList}
            onPass={this.invoiceNumberPass}
            onClose={refresh => {
              this.setState({ autoAuditErrorList: [] });
              refresh && this.props.afterClose(true);
            }}
          />
        )}
        {/*加签弹框*/}
        {addSignVisible && (
          <ModalAddSign
            visible={addSignVisible}
            info={Object.assign(addSignInfo, { approvalTxt: this.approveBarRef.props.form.getFieldValue('reason') })}
            entityType={entityType}
            entityOID={entityOID}
            entityId={this.props.info.id}
            signCompanyOIDs={companyOIDs}
            onBackSign={params => {
              this.setState({ addSignVisible: false, addSignInfo: params });
              this.approveBarRef.handleSelectAddition(params);
              this.approveBarRef.props.form.setFieldsValue({ reason: params.approvalTxt });
            }}
            close={success => {
              this.setState({ addSignVisible: false });
              success && this.goBack(true);
            }}
          />
        )}
      </Affix>
    ) : (
      <Affix offsetBottom={0} className={`bottom-bar${fullWidth ? ' full-width' : ''}`}>
        <If value={certificateVisible}>
          <Button type="primary"
                  style={{marginRight: 10}}
                  onClick={this.handlePrintCertificate}>{messages('expense-14.key24')/*打印凭证*/}</Button>
        </If>
        <Button className="back-btn" onClick={() => this.goBack()}>{messages('common.back')/*返回*/}</Button>
      </Affix>
    )
  }
}

AuditApplicationDetail.propTypes = {
  entityOID: React.PropTypes.string,
  entityType: React.PropTypes.number,
  status: React.PropTypes.number,//单据状态
  afterClose: React.PropTypes.func,
  applicantOID: React.PropTypes.string,
  companyOid: React.PropTypes.string,
  businessCode: React.PropTypes.string,
  parentBusinessCode: React.PropTypes.string,
  selectedExpense: React.PropTypes.array,
  selectedInvoice: React.PropTypes.array,
};

AuditApplicationDetail.defaultProps = {
  afterClose: () => {},
  selectedExpense: [],
  selectedInvoice: [],
};

AuditApplicationDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    company: state.login.company,
    loginUser: state.login.loginUser,
    options: state.login.options,
  }
}

export default connect(mapStateToProps)(AuditApplicationDetail)
